# -*- coding: utf-8 -*-
import codecs

from apina import Apina

if __name__ == "__main__":
    import time, random


    def funk(id, url):
        print "id: " + id + ", url: " + url
    import eiupata

    api = Apina()
    info = eiupata.login()
    if api.login(info['user'], info['password']):
#        wt = api.get_wikitext([u"testi"])
#        print unicode(wt)
        #api.edit_page(u"Käyttäjä:HunsBot/Testi", "testi", 0, "testi", funk)
#        api.undo_last(u"Käyttäjä:HunsBot/Testi", 0, "", funk)
 

#        print "tulos1: \n{0}\n".format(al)
#        print "numero 3: " + str(al[3])

        ticket = None
        lst = None
        while True:
            if lst: ticket = lst.ticket 

#	    try:
            lst = api.category_members(category=u"Luokka:Suomen substantiivien mallineet", continu=ticket, limit=100)
            #except error:
             #   break 

            titles = map(lambda a: a['title'], lst)
            print "TITLES: {}".format(titles)

            pages = api.get_wikitext(titles)
            for pgid in pages:
                t = pages[pgid]['title']
                page = pages[pgid]
                if page:
                    if 'revisions' in page:
                        rev = page['revisions'][0]
                        if rev:
                            if '*' in rev: 
                                wtxt = rev['*']
                                print u"Kirjoitetaan {}".format(t)
                                f = codecs.open(u"haetut/" + t, "w", "utf-8", "replace")
                                f.write(wtxt)
                                f.close()

            if not lst.continues():
                break


        f.close()
        

